﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessObject;
using Entity;
using DataAccess;
using System.Windows.Forms;

namespace StudentAttendanceChecking.Controls
{
    public class TreeMain
    {

        public static void loadTreeMain(TreeView tv) {
            //add root tree node
            createParentNode(tv.Nodes, "root", "User", 0, 0);

            //add branch tree node
            loadBranches(tv.Nodes["root"]);

        }

        private static void loadBranches(TreeNode tn)
        {
            try
            {
                BranchBO branchBO = new BranchBO(BranchDA.generateBranch());
                foreach (Branch br in branchBO.Branches)
                {
                    createChildNode(tn, br.BranchID.ToString(), br.ToString(), 1, 2);
                    //add class tree node
                    loadClasses(tn.Nodes[br.BranchID.ToString()]);
                }
            }
            catch (Exception ex) {
                MessageBox.Show("loadBranches: " + ex.Message);
            }
        }

        private static void loadClasses(TreeNode tn)
        {
            try
            {
                ClassBO classBO = new ClassBO(ClassDA.generateClass(new Branch{BranchID=Int32.Parse(tn.Name)}));
                foreach (Classs cl in classBO.Classes)
                {
                    createChildNode(tn, cl.ClassID.ToString(), cl.ToString(), 3, 4);

                    //add student tree node
                    loadStudent(tn.Nodes[cl.ClassID.ToString()]);
                }
            }
            catch (Exception ex) {
                MessageBox.Show("loadClasses: " + ex.Message);
            }
        }

        private static void loadStudent(TreeNode tn) 
        {
            try
            {
                StudentBO studentBO = new StudentBO(StudentDA.generateStudent(new Classs { ClassID= Int32.Parse(tn.Name) }));
                foreach (Student student in studentBO.Students)
                {
                    createChildNode(tn,student.StudentID.ToString(),student.ToString(),5,6);
                }
            }
            catch(Exception ex){
                MessageBox.Show("loadStudent: " + ex.Message);
            }
        }

        private static void createParentNode(TreeNodeCollection tnc,String strKey,String strName,Int32 iImage,Int32 iSelectImage) 
        {
            tnc.Add(strKey,strName,iImage,iSelectImage);
        }

        private static void createChildNode(TreeNode tn, String strKey, String strName, Int32 iImage, Int32 iSelectImage)
        {
            tn.Nodes.Add(strKey, strName, iImage, iSelectImage);
        }
    }
}